/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.matching;

import mosdi.fa.SuffixAutomaton;
import mosdi.util.ArrayUtils;
import mosdi.util.BitArray;

public class BNDMatcher extends AbstractMatcher {

	/** Suffix automaton of reverse pattern. */
	private SuffixAutomaton suffixAutomaton;
	
	public BNDMatcher(int alphabetSize, int[] pattern) {
		super(alphabetSize, pattern);
		this.suffixAutomaton = new SuffixAutomaton(alphabetSize, ArrayUtils.reverseCopy(pattern));
	}

	@Override
	protected WindowData processWindow(int[] text, int windowEndPos) {
		// longest pattern prefix that is also suffix of the search window 
		int longestPrefix = 0;
		int cost = 0;
		BitArray activeStates = suffixAutomaton.startStates();
		int i=0;
		for (; i<pattern.length; ++i) {
			cost += 1;
			activeStates = suffixAutomaton.transition(activeStates, text[windowEndPos-i]);
			if (!suffixAutomaton.isFactor(activeStates)) break;
			if ((i<pattern.length-1) && suffixAutomaton.isSuffix(activeStates)) longestPrefix = i+1;
		}
		return new WindowData(i==pattern.length, pattern.length-longestPrefix, cost);
	}
	
	@Override
	public int findMatches(int[] text) {
		characterAccesses = 0;
		int matches = 0;
		// last position of search window
		int pos = pattern.length - 1; 
		while (pos<text.length) {
			WindowData wd = processWindow(text, pos);
			if (wd.match) matches += 1;
			pos += wd.shift;
			characterAccesses += wd.cost;
		}
		return matches;
	}

}
